#pragma once
#include <functional>
#include <memory>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
namespace Message_MQ{


//
class ThreadPool {
public:
    ThreadPool(size_t numThreads = std::thread::hardware_concurrency());
    ~ThreadPool();

    using self_ptr = std::shared_ptr<ThreadPool>;
    //允许停止之后将任务送入线程池，但是此时并不会执行，也不会再有新的效果
    template<typename F, typename... Args>
    auto enqueue(F&& f, Args&& ...args)-> std::future<decltype(f(args...))>
    {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared< std::packaged_task<return_type()> >(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );
        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            tasks.emplace_back([task](){ (*task)(); });
        }
        condition.notify_one();
        return res;
    }




private:
    void thread_work();
    void stop();
    // need to keep track of threads so we can join them
    std::vector<std::thread> workers;
    // container for work
    std::vector<std::function<void()>> tasks;

    // synchronization
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool _stop;
};
void ThreadPool::thread_work()
{
    std::vector<std::function<void()>> MyTasks;
    while(true)
    {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            if(_stop && tasks.empty())
                return;
            condition.wait(lock, [this] { return _stop || !tasks.empty(); });
            MyTasks.swap(tasks);
        }
        for(auto& task : MyTasks)
            task();
        MyTasks.clear();
    }
}
ThreadPool::ThreadPool(size_t numThreads)
{
    _stop = false;
    for(size_t i = 0; i < numThreads; ++i)
        workers.emplace_back(
            [this]
            {
                thread_work();
            }
        );
}

inline ThreadPool::~ThreadPool()
{
    stop();
}

void ThreadPool::stop()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        _stop = true;
    }
    condition.notify_all();
    for(std::thread &worker: workers)
        worker.join();
}


};